﻿using System;
using System.Drawing;
using System.IO;

namespace ProjectN.Core.Instance
{
    /// <summary>
    /// 图片文件管理器，专门处理图像文件存储
    /// </summary>
    public sealed class ImageCollection : ResourceCollection<ImageResource>
    {
        /// <summary>
        /// 初始化图片管理器实例
        /// </summary>
        /// <param name="storagePath">图片存储目录路径</param>
        public ImageCollection(string storagePath) : base(storagePath) { }

        /// <inheritdoc/>
        protected override ImageResource CreateHandler(string hash, string extension)
            => new ImageResource(this, hash, extension);
    }

    /// <summary>
    /// 图片处理器，提供图像文件访问功能
    /// </summary>
    public sealed class ImageResource : ResourceItem<ImageResource>
    {
        private Image? _image;

        /// <summary>
        /// 获取图像对象（延迟加载）
        /// </summary>
        /// <exception cref="FileNotFoundException">当对应的图片文件不存在时抛出</exception>
        /// <exception cref="ObjectDisposedException">对象已释放时抛出</exception>
        public Image Image
        {
            get
            {
                ObjectDisposedException.ThrowIf(_disposed, GetType().Name);
                if (_image == null)
                {
                    File.Refresh();
                    if (!File.Exists)
                        throw new FileNotFoundException("指定的图片文件不存在", File.FullName);
                    // 使用共享读模式加载图像以避免文件锁定
                    using var fs = new FileStream(
                        File.FullName,
                        FileMode.Open,
                        FileAccess.Read,
                        FileShare.ReadWrite);
                    _image = Image.FromStream(fs);
                }
                return _image;
            }
        }

        /// <summary>
        /// 初始化图片处理器实例
        /// </summary>
        /// <param name="manager">所属的图片管理器</param>
        /// <param name="hash">图片哈希值</param>
        /// <param name="extension">图片扩展名</param>
        internal ImageResource(ImageCollection manager, string hash, string extension)
            : base(manager, hash, extension) { }

        private bool _disposed;

        /// <inheritdoc/>
        public override void Dispose()
        {
            // 释放图像资源
            _image?.Dispose();
            base.Dispose();
            _disposed = true;
        }
    }
}
